//
//  WKTextViewExtension.swift
//  NewDelivery
//
//  Created by 天下宅 on 2016/11/8.
//  Copyright © 2016年 天下宅. All rights reserved.
//

import Foundation
import UIKit
private var wkTextViewPlaceHolder = "wkTextViewPlaceHolder"
extension UITextView
{
    private var placeHolderLabel:UILabel?
        {
        set(newValue){
            objc_setAssociatedObject(self, &wkTextViewPlaceHolder, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            
        }
        
        get{
            let count = (objc_getAssociatedObject(self, &wkTextViewPlaceHolder) ?? 0) as? UILabel
            return count
        }
    }
    
    var placeHolder:String
        {
        set(newValue){
            if placeHolderLabel == nil
            {
                placeHolderLabel = UILabel()
                placeHolderLabel!.textColor = UIColor.lightGray
                placeHolderLabel!.font = self.font
                self.addSubview(placeHolderLabel!)
                placeHolderLabel!.snp.makeConstraints { (make) in
                    make.left.equalToSuperview().offset(5)
                    make.top.equalToSuperview().offset(5)
                    make.width.equalToSuperview()
                    make.height.equalTo(20)
                }
                NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            }
            placeHolderLabel!.text = newValue
            placeHolderLabel!.isHidden = placeHolderLabel!.text!.characters.count <= 0
        }
        
        get{
            return placeHolderLabel?.text ?? ""
        }
    }
    
    func textChange()
    {
        placeHolderLabel!.isHidden = self.text.characters.count > 0
    }
    
    
}
